package com.software.loginregister.activity;

import androidx.appcompat.app.AppCompatActivity;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.Color;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.Toast;

import com.software.loginregister.MainActivity;
import com.software.loginregister.R;
import com.software.loginregister.adapter.TasteAdapter;
import com.software.loginregister.api.UserApi;
import com.software.loginregister.api.UserHealthApi;
import com.software.loginregister.entity.Result;
import com.software.loginregister.entity.TasteItem;
import com.software.loginregister.entity.User;
import com.software.loginregister.entity.UserDetail;
import com.software.loginregister.entity.vo.UserTagDTO;
import com.software.loginregister.util.RetrofitClient;
import com.software.loginregister.util.SharedPreferencesUtil;

import java.util.ArrayList;
import java.util.List;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;

public class TasteSelectionActivity extends AppCompatActivity {

    private static final int SPAN_COUNT = 3;
    private List<TasteItem> tasteItems;
    private Button btnTasteSelectStart;
    private TasteAdapter adapter;
    private Long userId;
    private UserApi userApi;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_taste_selection);
        // 获取userId
        userId = getIntent().getLongExtra("userId", -1);
        if (userId == -1) {
            userId = SharedPreferencesUtil.getUserId(this);
        }
        // 初始化API
        userApi = RetrofitClient.getInstance().getUserApi();
        // 设置状态栏
        setStatusBar();
        // 初始化口味数据
        initTasteData();
        String currentTaste = getIntent().getStringExtra("currentTaste");
        // 初始化RecyclerView
        RecyclerView rvTastes = findViewById(R.id.rv_tastes);
        rvTastes.setLayoutManager(new GridLayoutManager(this, SPAN_COUNT));
        adapter = new TasteAdapter(tasteItems);

        // 如果有已选择的口味，显示选中状态
        String existingTastes = SharedPreferencesUtil.getTastePreferences(this);
        if (!TextUtils.isEmpty(currentTaste)) {
            String[] tastes = currentTaste.split("、");
            for (String taste : tastes) {
                for (TasteItem item : tasteItems) {
                    if (item.getName().equals(taste.trim())) {
                        item.setSelected(true);
                        break;
                    }
                }
            }
        }

        rvTastes.setAdapter(adapter);
        // 初始化按钮
        btnTasteSelectStart = findViewById(R.id.btn_taste_select_start);

        // 根据来源修改按钮文字
        if (getIntent().getBooleanExtra("fromHealthEdit", false)) {
            btnTasteSelectStart.setText("确认修改");
        }
        btnTasteSelectStart.setOnClickListener(v -> {
            List<TasteItem> selectedTastes = adapter.getSelectedItems();
            if (selectedTastes.isEmpty()) {
                Toast.makeText(this, "请至少选择一个口味偏好", Toast.LENGTH_SHORT).show();
                return;
            }
            saveUserTastes(selectedTastes);
        });
    }

    private void setStatusBar() {
        Window window = getWindow();
        // 设置状态栏背景为透明
        window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        window.setStatusBarColor(Color.TRANSPARENT);

        // 设置状态栏文字颜色为深色
        View decorView = window.getDecorView();
        int flags = decorView.getSystemUiVisibility();
        flags |= View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR;
        decorView.setSystemUiVisibility(flags);

    }

    private void initTasteData() {
        tasteItems = new ArrayList<>();
        tasteItems.add(new TasteItem("快餐", R.drawable.ic_fastfood));
        tasteItems.add(new TasteItem("清淡", R.drawable.ic_light));
        tasteItems.add(new TasteItem("油炸", R.drawable.ic_fry));
        tasteItems.add(new TasteItem("爽口", R.drawable.ic_tangy));
        tasteItems.add(new TasteItem("酱汁", R.drawable.ic_sauce));
        tasteItems.add(new TasteItem("拌类", R.drawable.ic_mixed));
        tasteItems.add(new TasteItem("甜品", R.drawable.ic_dessert));
        tasteItems.add(new TasteItem("养生", R.drawable.ic_healthpreservation));
        tasteItems.add(new TasteItem("大鱼大肉", R.drawable.ic_richfood));
    }

    private void saveUserTastes(List<TasteItem> selectedTastes) {
        // 构建请求数据
        List<UserTagDTO> userTags = new ArrayList<>();
        // 构建口味偏好字符串
        StringBuilder tastePreferences = new StringBuilder();

        for (int i = 0; i < selectedTastes.size(); i++) {
            TasteItem taste = selectedTastes.get(i);
            // 添加到用户标签
            UserTagDTO tag = new UserTagDTO();
            tag.setUserId(userId);
            tag.setTagName(taste.getName());
            userTags.add(tag);

            // 构建口味偏好字符串
            tastePreferences.append(taste.getName());
            if (i < selectedTastes.size() - 1) {
                tastePreferences.append("、");
            }
        }
        // 保存口味偏好到SharedPreferences
        SharedPreferencesUtil.saveTastePreferences(this, tastePreferences.toString());
        // 调用API保存用户口味标签
        userApi.saveUserTags(userTags).enqueue(new Callback<Result<Boolean>>() {
            @Override
            public void onResponse(Call<Result<Boolean>> call, Response<Result<Boolean>> response) {
                if (response.isSuccessful() && response.body() != null && response.body().getCode() == 1) {
                    // 保存成功后，更新健康信息
                    updateHealthInfo(tastePreferences.toString());
                } else {
                    Toast.makeText(TasteSelectionActivity.this,
                            "保存失败: " + (response.body() != null ? response.body().getMsg() : "未知错误"),
                            Toast.LENGTH_SHORT).show();
                }
            }

            @Override
            public void onFailure(Call<Result<Boolean>> call, Throwable t) {
                Toast.makeText(TasteSelectionActivity.this,
                        "网络错误: " + t.getMessage(),
                        Toast.LENGTH_SHORT).show();
            }
        });
    }

    private void updateHealthInfo(String preferences) {
        // 先获取现有的健康信息
        RetrofitClient.getInstance()
                .create(UserHealthApi.class)
                .getUserHealth(userId)
                .enqueue(new Callback<Result<UserDetail>>() {
                    @Override
                    public void onResponse(Call<Result<UserDetail>> call, Response<Result<UserDetail>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            // 获取现有数据
                            UserDetail existingDetail = response.body().getData();
                            // 如果没有现有数据，创建新的
                            if (existingDetail == null) {
                                existingDetail = new UserDetail();
                            }

                            // 更新口味偏好，保留其他数据
                            existingDetail.setUserId(userId);
                            existingDetail.setTaste(preferences);

                            // 更新健康信息
                            updateUserHealthDetail(existingDetail);
                        } else {
                            // 如果获取失败，仅更新口味偏好
                            UserDetail newDetail = new UserDetail();
                            newDetail.setUserId(userId);
                            newDetail.setTaste(preferences);
                            updateUserHealthDetail(newDetail);
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<UserDetail>> call, Throwable t) {
                        Log.e("TasteSelection", "Failed to get health info", t);
                        // 如果获取失败，仅更新口味偏好
                        UserDetail newDetail = new UserDetail();
                        newDetail.setUserId(userId);
                        newDetail.setTaste(preferences);
                        updateUserHealthDetail(newDetail);
                    }
                });
    }

    private void updateUserHealthDetail(UserDetail userDetail) {
        RetrofitClient.getInstance()
                .create(UserHealthApi.class)
                .updateUserHealth(userId, userDetail)
                .enqueue(new Callback<Result<String>>() {
                    @Override
                    public void onResponse(Call<Result<String>> call, Response<Result<String>> response) {
                        if (response.isSuccessful() && response.body() != null
                                && response.body().getCode() == 1) {
                            // 保存到本地缓存
                            saveToLocalCache(userDetail);

                            // 全部保存成功
                            SharedPreferencesUtil.setTasteSelected(TasteSelectionActivity.this, true);

                            // 根据场景决定跳转
                            if (getIntent().getBooleanExtra("fromHealthEdit", false)) {
                                // 如果是从健康编辑页面来的，返回上一页
                                setResult(RESULT_OK);
                                finish();
                            } else {
                                // 否则跳转到主页
                                Intent intent = new Intent(TasteSelectionActivity.this, MainActivity.class);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK | Intent.FLAG_ACTIVITY_CLEAR_TASK);
                                startActivity(intent);
                                finish();
                            }
                        } else {
                            Toast.makeText(TasteSelectionActivity.this,
                                    "健康信息更新失败",
                                    Toast.LENGTH_SHORT).show();
                        }
                    }

                    @Override
                    public void onFailure(Call<Result<String>> call, Throwable t) {
                        Toast.makeText(TasteSelectionActivity.this,
                                "网络错误: " + t.getMessage(),
                                Toast.LENGTH_SHORT).show();
                    }
                });
    }

    private void saveToLocalCache(UserDetail userDetail) {
        SharedPreferences prefs = getSharedPreferences("user_health", MODE_PRIVATE);
        SharedPreferences.Editor editor = prefs.edit();

        // 保存所有健康信息
        if (userDetail.getHeight() != null) {
            editor.putFloat("height", userDetail.getHeight().floatValue());
        }
        if (userDetail.getWeight() != null) {
            editor.putFloat("weight", userDetail.getWeight().floatValue());
        }
        if (userDetail.getBmi() != null) {
            editor.putFloat("bmi", userDetail.getBmi().floatValue());
        }
        if (userDetail.getBmiStatus() != null) {
            editor.putString("bmi_status", userDetail.getBmiStatus());
        }
        if (userDetail.getTaste() != null) {
            editor.putString("taste", userDetail.getTaste());
        }
        if (userDetail.getAllergen() != null) {
            editor.putString("allergen", userDetail.getAllergen());
        }
        if (userDetail.getDietaryRestrictions() != null) {
            editor.putString("dietary_restrictions", userDetail.getDietaryRestrictions());
        }

        editor.apply();
    }
}